<?php
namespace app\api\controller;

use TencentCloud\Common\Credential;
use TencentCloud\Common\Profile\ClientProfile;
use TencentCloud\Common\Profile\HttpProfile;
use TencentCloud\Common\Exception\TencentCloudSDKException;
use TencentCloud\Ocr\V20181119\OcrClient;
use TencentCloud\Ocr\V20181119\Models\IDCardOCRRequest;
use TencentCloud\Faceid\V20180301\FaceidClient;
use TencentCloud\Faceid\V20180301\Models\DetectAuthRequest;
use TencentCloud\Faceid\V20180301\Models\GetDetectInfoRequest;
use think\Controller;
use think\Db;

/**
 * 实名认证
 * Class Authentication
 * @package app\api\controller
 */
class Authentication extends Controller
{
    const SIDE_FRONT = 'FRONT';//正面
    const SIDE_BACK = 'BACK';//背面

    private $cred;

    protected function _initialize()
    {
        parent::_initialize();
        $this->cred   = new Credential("AKIDFQ7i7KXFwRltpZfagVtQOYXJ1cR6uqwD", "EHCuQlxynQr6JSSGtJvpW2MezUwGRUOH");
    }

    /**
     * 识别身份证信息
     * @param string $file
     * @param int $type
     */
    public function id_card($file = '',$type = 0,$cropIdCard = false,$cropPortrait = false){
        try {

            $httpProfile = new HttpProfile();
            $httpProfile->setEndpoint("ocr.tencentcloudapi.com");

            $clientProfile = new ClientProfile();
            $clientProfile->setHttpProfile($httpProfile);
            $client = new OcrClient($this->cred, "ap-beijing", $clientProfile);

            $req = new IDCardOCRRequest();

            $params = [];
            if( stripos($file,'https://') === FALSE && stripos($file,'http://') === FALSE ){
                $params['ImageBase64'] = $file;
            }else{
                $params['ImageUrl'] = $file;
            }

            $params['CardSide'] = $type ? self::SIDE_BACK : self::SIDE_FRONT;
            if( $cropIdCard && !$cropPortrait ){
                $params['Config'] = '{"CropIdCard":true}';//$cropIdCard;
            } elseif( $cropPortrait && !$cropIdCard ){
                $params['Config'] = '{"CropPortrait":true}';//$cropPortrait;
            }elseif( $cropIdCard && $cropPortrait ){
                $params['Config'] = '{"CropIdCard":true,"CropPortrait":true}';
            }
            $req->fromJsonString(json_encode($params));
            $resp = $client->IDCardOCR($req);

            $json = $resp->toJsonString();
            $jsonObj = json_decode($json,true);

            //var_dump($jsonObj);
            //

            if(isset($jsonObj['Error'])){
                $result = [
                    'status' => 'fail',
                    'message' => $jsonObj['Error']['Message']
                ];
            }else{
                $result = [
                    'status' => 'ok',
                    'message' => 'OK',
                    'data' => $jsonObj
                ];
            }

        }
        catch(TencentCloudSDKException $e){
            return [
                'status' => 'fail',
                'message' => $e
            ];
        }

        return $result;
    }


    /**
     * 人脸比对
     * @param string $file
     * @param int $type
     */
    public function face_alignment($TerminalType = '',$IdCard = '',$Name = '',$RedirectUrl = '',$Extra = '',$RuleId = '',$ImageBase64 = ''){
        try {

            $httpProfile = new HttpProfile();
            $httpProfile->setEndpoint("faceid.tencentcloudapi.com");

            $clientProfile = new ClientProfile();
            $clientProfile->setHttpProfile($httpProfile);
            $client = new FaceidClient($this->cred, "ap-beijing", $clientProfile);

            $req = new DetectAuthRequest();

            $params = [];
            $params['TerminalType'] = $TerminalType;
            $params['IdCard'] = $IdCard;
            $params['Name'] = $Name;
            $params['RedirectUrl'] = $RedirectUrl;
            $params['Extra'] = $Extra;
            $params['RuleId'] = $RuleId;
            $params['ImageBase64'] = $ImageBase64;

            //var_dump($params);

            $req->fromJsonString(json_encode($params));

            $resp = $client->DetectAuth($req);

            $json = $resp->toJsonString();
            $jsonObj = json_decode($json,true);

            //var_dump($jsonObj);

            if(isset($jsonObj['Url'])){
                    $result = [
                        'status' =>  'ok',
                        'message' => $jsonObj['Url']
                    ];
            }else{
                $result = [
                    'status' =>  'fail',
                    'message'   => $jsonObj['message']
                ];
            }
        }
        catch(TencentCloudSDKException $e) {
            $result = [
                'status' =>  'fail',
                'message'   => $e
            ];
        }

        return $result;
    }


    /**
     * 认证结果
     * @param string $BizToken
     * @param string $RuleId
     * @param string $InfoType取值（0：全部；1：文本类；2：身份证正反面；3：视频最佳截图照片；4：视频）
     */
    public function authentication_result($BizToken = '',$RuleId = '5',$InfoType = '1'){
        try {

            $httpProfile = new HttpProfile();
            $httpProfile->setEndpoint("faceid.tencentcloudapi.com");
            $clientProfile = new ClientProfile();
            $clientProfile->setHttpProfile($httpProfile);
            $client = new FaceidClient($this->cred, "ap-beijing", $clientProfile);

            $req = new GetDetectInfoRequest();

            $params = [];
            $params['BizToken'] = $BizToken;
            $params['RuleId'] = $RuleId;
            $params['InfoType'] = $InfoType;

            //var_dump($params);
            $req->fromJsonString(json_encode($params));

            $resp = $client->GetDetectInfo($req);

            $json = $resp->toJsonString();

            $json = json_decode($json,true);

            $jsonObj=(array)json_decode($json['DetectInfo'],true);

            if(isset($jsonObj['Text']['ErrMsg'])=='成功'){
                $result = [
                    'status' =>  'ok',
                    'message' => $jsonObj['Text']['ErrMsg'],
                     'data' => $jsonObj['Text']
                ];
            }else{
                $result = [
                    'status' =>  'fail',
                    'message'   => $jsonObj['Text']['ErrMsg']
                ];
            }
        }
        catch(TencentCloudSDKException $e) {
            $result = [
                'status' =>  'fail',
                'message'   => $e
            ];
        }

        return $result;
    }

}